#include <iostream>
#include <modbus.h>

int main() {
    // 创建modbus连接句柄
    modbus_t *mb = modbus_new_rtu("/dev/ttyS0", 9600, 'N', 8, 1);
    if (mb == NULL) {
        std::cerr << "Unable to create the modbus context" << std::endl;
        return -1;
    }

    // 设置从设备ID
    modbus_set_slave(mb, 1);

    // 连接到Modbus RTU从设备
    int conn = modbus_connect(mb);
    if (conn == -1) {
        std::cerr << "Connection failed: " << modbus_strerror(errno) << std::endl;
        modbus_free(mb);
        return -1;
    }

    // 定义要读取的寄存器地址和数量
    uint16_t tab_reg[1];
    int addr = 0; // 起始地址
    int nb = 1;   // 寄存器数量

    // 读取寄存器
    int rc = modbus_read_registers(mb, addr, nb, tab_reg);
    if (rc == -1) {
        std::cerr << "Failed to read registers: " << modbus_strerror(errno) << std::endl;
        modbus_free(mb);
        return -1;
    }

    // 打印读取到的寄存器值
    std::cout << "Register value: " << tab_reg[0] << std::endl;

    // 断开连接并释放资源
    modbus_close(mb);
    modbus_free(mb);

    return 0;
}
//添加环境：export LD_LIBRARY_PATH=/usr/local/lib
//编译命令：g++ -o run_modbus_rtu_client test_modbus_rtu_client.cpp -I/usr/local/include/modbus -lmodbus

